package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.mapper.StrategyMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {
    @Autowired
    private StrategyDetailMapper detailMapper;
    @Autowired
    private StrategyContentMapper contentMapper;


    public PageInfo queryForList(QueryObject qo){
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderby());
        List<StrategyDetail> list = detailMapper.selectForList(qo);
        return new PageInfo(list);
    }

    public void saveOrUpdate(StrategyDetail detail) {
        StrategyContent content = detail.getStrategyContent();

        if (detail.getState()==true) {
            detail.setReleaseTime(new Date());
        }

        if (detail.getSequence() == null) {
            int maxSequence = detailMapper.selectMaxSequence(detail.getCatalog().getId());
            detail.setSequence(maxSequence + 1);
        }

        if (detail.getId() != null) {
            detailMapper.updateByPrimaryKey(detail);
            content.setId(detail.getId());
            contentMapper.updateByPrimaryKey(content);
        }else {
            detail.setCreateTime(new Date());
            detailMapper.insert(detail);
            content.setId(detail.getId());
            contentMapper.insert(content);
        }
    }

    public StrategyContent getContentById(Long detailId) {
        return contentMapper.selectByPrimaryKey(detailId);
    }

    public StrategyDetail getById(Long catalogId) {
        return detailMapper.selectByPrimaryKey(catalogId);
    }
}
